<script setup>
import PageContainer from '@/components/PageContainer.vue'
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getUserInfoService, updateUserInfoService } from '@/api/user'
import { useUserStore } from '@/stores'
const userStore = useUserStore()

const formRef = ref(null)
const form = reactive({
  username: '',
  nickname: '',
  email: ''
})
Object.assign(form, userStore.user)
const rules = reactive({
  nickname: [
    { required: true, message: '请输入用户昵称', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    {
      type: 'email',
      message: '请输入正确的邮箱地址',
      trigger: ['blur', 'change']
    }
  ]
})

onMounted(async () => {
  try {
    const userInfo = await getUserInfoService()
    Object.assign(form, userInfo.data)
  } catch (error) {
    console.error(error)
  }
})

const submitForm = async () => {
  try {
    await formRef.value.validate()
    await updateUserInfoService(form)
    try {
      const res = await getUserInfoService()
      userStore.user = res.data
    } catch (error) {
      console.error(error)
    }
    ElMessage('更新成功')
  } catch (error) {
    console.error(error)
  }
}

const resetForm = () => {
  formRef.value.resetFields()
}
</script>
<template>
  <page-container title="用户信息">
    <el-row>
      <el-col :span="12">
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="120px"
          class="demo-ruleForm"
        >
          <el-form-item label="登录名称" prop="username">
            <el-input v-model="form.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="用户昵称" prop="nickname">
            <el-input v-model="form.nickname"></el-input>
          </el-form-item>
          <el-form-item label="用户邮箱" prop="email">
            <el-input v-model="form.email"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm">提交修改</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form></el-col
      >
    </el-row>
  </page-container>
</template>
<style scoped>
/* .demo-ruleForm {
  max-width: 400px;
  margin: auto;
} */
</style>
